<template>
  <el-container>
    <el-form label-width="80px" label-position="left" size="small">
      <el-form-item label="代理名称">
        <el-input v-model="formData.proxyName" placeholder="请输入"></el-input>
      </el-form-item>

      <el-form-item label="真实姓名">
        <el-input v-model="formData.name" placeholder="请输入"></el-input>
      </el-form-item>

      <el-form-item label="手机号">
        <el-input v-model="formData.phoneNumber" placeholder="请输入"></el-input>
      </el-form-item>

      <el-form-item label="密码">
        <el-input v-model="formData.password" type="password" placeholder="请输入"></el-input>
      </el-form-item>

      <el-form-item label="代理区域">
        <el-input v-model="formData.proxyRegion" placeholder="请输入"></el-input>
      </el-form-item>

      <el-form-item label="是否启用">
        <el-switch
          v-model="formData.enable"
          active-value="1"
          inactive-value="0">
        </el-switch>
      </el-form-item>

      <el-form-item label="代理区域">
        <el-col :span="6">
          <el-form-item label="经度">
            <el-input v-model="formData.serviceCenter.location.O" placeholder="请输入内容"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="1">
          <el-form-item label="纬度">
            <el-input v-model="formData.serviceCenter.location.P" placeholder="请输入内容"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="1">
          <el-button type="primary"  data-toggle="modal"
                     data-target="#exampleModalCenter">选择坐标</el-button>
        </el-col>
      </el-form-item>

      <el-form-item label="服务区域">
        <el-col :span="8">
          <h3>区域及配送范围</h3>

          <div class="mapconfig-info" v-for="(serviceRegionItem,index) in formData.serviceRegionGroup">
            <p>配送范围</p>
            <p>
              首重 {{serviceRegionItem.weight}} , 价格 {{serviceRegionItem.weightprice}} 元;
              续重 {{serviceRegionItem.distance}} ,价格{{serviceRegionItem.distanceprice}} 元;
              起步距离 {{serviceRegionItem.sdistance}} , 价格{{serviceRegionItem.sdistanceprice}} 元;
              增加距离 {{serviceRegionItem.addstart}} , 价格{{serviceRegionItem.addstartprice}} 元;
            </p>
            <div>
              <el-button type="info" class="pull-right" size="mini" @click="editorMapConfig({index:index})">开启编辑</el-button>
            </div>
          </div>

          <div class="add-mapconfig" v-if="mapConfigForm.editorStatus == 1">
            <el-row>
              <el-col :span="4">
                配送范围
              </el-col>
              <el-col :span="11" offset="9">
                <el-button size="mini" type="info" @click="closeAddMapConfig()">取消</el-button>
                <el-button size="mini" type="success" @click="saveMapConfig()">保存</el-button>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="4">
              首重
              </el-col>
              <el-col :span="9" offset="1">
                <el-input v-model="mapConfigForm.weight" size="mini" placeholder="请输入kg" ></el-input>
              </el-col>
              <el-col :span="9" offset="1">
                <el-input v-model="mapConfigForm.weightprice" size="mini" placeholder="请输入价格" ></el-input>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="4">
                续重
              </el-col>
              <el-col :span="9" offset="1">
                <el-input v-model="mapConfigForm.distance" size="mini" placeholder="请输入kg" ></el-input>
              </el-col>
              <el-col :span="9" offset="1">
                <el-input v-model="mapConfigForm.distanceprice" size="mini" placeholder="请输入价格" ></el-input>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="4">
                起步距离
              </el-col>
              <el-col :span="9" offset="1">
                <el-input v-model="mapConfigForm.sdistance" size="mini" placeholder="请输入kg" ></el-input>
              </el-col>
              <el-col :span="9" offset="1">
                <el-input v-model="mapConfigForm.sdistanceprice" size="mini" placeholder="请输入价格" ></el-input>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="4">
                增加距离
              </el-col>
              <el-col :span="9" offset="1">
                <el-input v-model="mapConfigForm.addstart" size="mini" placeholder="请输入kg" ></el-input>
              </el-col>
              <el-col :span="9" offset="1">
                <el-input v-model="mapConfigForm.addstartprice" size="mini" placeholder="请输入价格" ></el-input>
              </el-col>
            </el-row>

          </div>

          <el-button size="small" type="primary" @click="openAddMapConfig()" icon="fa fa-plus-square">
            新增配送区域
          </el-button>
        </el-col>
        <el-col :span="16">
          <div id="map-container" class="map-container"></div>
        </el-col>
      </el-form-item>

      <el-form-item>
        <el-button type="success" @click="sendRequest()">立即保存</el-button>
        <el-button @click="goBack()">返回</el-button>
      </el-form-item>
    </el-form>

    <!-- 地图选择 -->
    <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog"
         aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered address-map-container" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <div class="modal-title" id="exampleModalLongTitle">
              <el-col :span="5">选择我的位置</el-col>
              <!--<el-col :span="10" :offset="1">选择我的位置</el-col>-->
              <el-form size="mini" label-width="50px" style="margin: 0">
                <el-col :span="9" :offset="7">
                  <el-form-item style="margin: 0">
                    <el-input v-model="addressSearchForm.keywords" placeholder="请输入需要搜索的位置">
                      <el-button slot="prepend" icon="fa fa-fw fa-map-marker"></el-button>
                      <el-button  slot="append" size="mini" icon="fa fa-fw fa-search" @click="searchKeywords()">搜索</el-button>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-form>
            </div>
          </div>
          <div class="modal-body">
            <div id="mapContainer" class="address-map"></div>
          </div>
          <div class="modal-footer">
            <el-button size="small" type="info" data-dismiss="modal">关闭</el-button>
            <el-button size="small" type="success" data-dismiss="modal"
                    @click="saveServiceCenterPoint()">确认
            </el-button>
          </div>
        </div>
      </div>
    </div>

  </el-container>
</template>
<script>
  export default {
    methods: {
      goBack: function () {
        this.$router.go(-1)
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      openAddMapConfig: function () { // 打开添加地图配置项
        if (!this.formData.serviceCenter.isSelect) {
          this.$message({
            showClose: true,
            message:'请配置代理服务中心点',
            type: 'warning'
          });
          return false
        }
        if (this.mapConfigForm.editorStatus == 1) {
          this.$message({
            showClose: true,
            message:'请先保存目前正在编辑的配置项',
            type: 'warning'
          });
          return false;
        }
        this.mapConfigForm = {
          editorStatus: 1,
          beginPrice: '',
          deliverPrice: '',
          fullSubtractionPrice: '',
          currentEditorIndex: -1
        };
        polygonDrawUtil.beginDraw();
      },
      closeAddMapConfig: function () {    // 关闭添加地图配置项
        this.mapConfigForm.editorStatus = 0;
        polygonDrawUtil.closeDrawSlsoClear();
      },
      saveMapConfig: function () {    // 保存区域划分配置
        let currentEditorIndex = this.mapConfigForm.currentEditorIndex;
        if (currentEditorIndex > -1) {
          polygonDrawUtil.polyEditorSave({
            map: map,
            PolygonObject: this.formData.serviceRegionGroup[currentEditorIndex].location
          });
          this.formData.serviceRegionGroup[currentEditorIndex].beginPrice = this.mapConfigForm.beginPrice;
          this.formData.serviceRegionGroup[currentEditorIndex].deliverPrice = this.mapConfigForm.deliverPrice;
          this.formData.serviceRegionGroup[currentEditorIndex].fullSubtractionPrice = this.mapConfigForm.fullSubtractionPrice;
          //增加
          this.formData.serviceRegionGroup[currentEditorIndex].weight = this.mapConfigForm.weight;
          this.formData.serviceRegionGroup[currentEditorIndex].distance = this.mapConfigForm.distance;
          this.formData.serviceRegionGroup[currentEditorIndex].sdistance = this.mapConfigForm.sdistance;
          this.formData.serviceRegionGroup[currentEditorIndex].addstart = this.mapConfigForm.addstart;
          this.formData.serviceRegionGroup[currentEditorIndex].weightprice = this.mapConfigForm.weightprice;
          this.formData.serviceRegionGroup[currentEditorIndex].distanceprice = this.mapConfigForm.distanceprice;
          this.formData.serviceRegionGroup[currentEditorIndex].sdistanceprice = this.mapConfigForm.sdistanceprice;
          this.formData.serviceRegionGroup[currentEditorIndex].addstartprice = this.mapConfigForm.addstartprice;
          this.mapConfigForm.currentEditorIndex = -1;
          this.mapConfigForm.editorStatus = 0;
        } else {
          let tempPoly = polygonDrawUtil.tempPolygon;
          if (!tempPoly) {  // 判断是否已经进行区域划分
            this.$message({
              showClose: true,
              message:'请配置坐标点',
              type: 'warning'
            });
            polygonDrawUtil.beginDraw();
            return false
          }
          let serviceRegion = {};
          this.$set(serviceRegion, 'beginPrice', this.mapConfigForm.beginPrice ? this.mapConfigForm.beginPrice : 0);
          this.$set(serviceRegion, 'deliverPrice', this.mapConfigForm.deliverPrice ? this.mapConfigForm.deliverPrice : 0);
          this.$set(serviceRegion, 'fullSubtractionPrice', this.mapConfigForm.fullSubtractionPrice ? this.mapConfigForm.fullSubtractionPrice : 0);
          this.$set(serviceRegion, 'location', tempPoly);
          //增加
          this.$set(serviceRegion, 'weight', this.mapConfigForm.weight ? this.mapConfigForm.weight : 0);
          this.$set(serviceRegion, 'distance', this.mapConfigForm.distance ? this.mapConfigForm.distance : 0);
          this.$set(serviceRegion, 'sdistance', this.mapConfigForm.sdistance ? this.mapConfigForm.sdistance : 0);
          this.$set(serviceRegion, 'addstart', this.mapConfigForm.addstart ? this.mapConfigForm.addstart : 0);
          this.$set(serviceRegion, 'weightprice', this.mapConfigForm.weightprice ? this.mapConfigForm.weightprice : 0);
          this.$set(serviceRegion, 'distanceprice', this.mapConfigForm.distanceprice ? this.mapConfigForm.distanceprice : 0);
          this.$set(serviceRegion, 'sdistanceprice', this.mapConfigForm.sdistanceprice ? this.mapConfigForm.sdistanceprice : 0);
          this.$set(serviceRegion, 'addstartprice', this.mapConfigForm.addstartprice ? this.mapConfigForm.addstartprice : 0);
          this.formData.serviceRegionGroup.push(serviceRegion);
          this.mapConfigForm.editorStatus = 0;
        }
      },
      editorMapConfig: function ({index: index}) {    // 编辑地图配置
        this.mapConfigForm = {
          editorStatus: 1,
          beginPrice: this.formData.serviceRegionGroup[index].beginPrice,
          deliverPrice: this.formData.serviceRegionGroup[index].deliverPrice,
          fullSubtractionPrice: this.formData.serviceRegionGroup[index].fullSubtractionPrice,
          //增加
          weight: this.formData.serviceRegionGroup[index].weight,
          distance: this.formData.serviceRegionGroup[index].distance,
          sdistance: this.formData.serviceRegionGroup[index].sdistance,
          addstart: this.formData.serviceRegionGroup[index].addstart,
          weightprice: this.formData.serviceRegionGroup[index].weightprice,
          distanceprice: this.formData.serviceRegionGroup[index].distanceprice,
          sdistanceprice: this.formData.serviceRegionGroup[index].sdistanceprice,
          addstartprice: this.formData.serviceRegionGroup[index].addstartprice,
          currentEditorIndex: index
        };
        polygonDrawUtil.polyEditor({map: map, PolygonObject: this.formData.serviceRegionGroup[index].location});
      },
      searchKeywords: function () {   // 关键字搜索
        let _this = this;
        let keywords = _this.addressSearchForm.keywords;
        // 关键字搜索
        AMap.service('AMap.PlaceSearch', function () {
          msearch = new AMap.PlaceSearch({
            map:map
          });
          msearch.search(keywords, function (status, result) {
            let poiList = result.poiList;
            if (poiList.count > 0) {
              let poi = poiList.pois[0].location;
              mapContainer.setCenter(poi);
              mapContainer.setZoom(16);
              _this.addressSearchForm.location = poi;
            }
          })
        });
      },
      saveServiceCenterPoint: function () {   // 保存中心坐标点
        this.formData.serviceCenter.location = this.addressSearchForm.location;
        this.formData.serviceCenter.isSelect = true;
        let icon = 'https://www.135k.com/addons/sd_liferuning/tp/public/static/home/img/shop_marker.png';
        polygonDrawUtil.addMarker({map: map, icon: icon, location: this.addressSearchForm.location})
      },
      sendRequest: function () {  // 发送提交请求
        let fromData = Object.assign(vm.formData, {});
        let serviceRegionGroup = fromData.serviceRegionGroup;
        if (serviceRegionGroup.length > 0) {
          serviceRegionGroup.forEach(function (item, index) {
            item.location = polygonDrawUtil.polyGetPath({PolygonObject: item.location});
          });
        }
        $.post('', {data: JSON.stringify(fromData)}, function (response) {
          if (response.code == 1) {
            alert('添加成功');
            location.href = 'index';
          } else {
            alert('添加失败');
          }
        }, 'json')
      }
    },
    data() {
      return {
        path: [],
        formData: {
          proxyName: '',  // 代理名称
          name: '',   // 姓名
          phoneNumber: '',   // 电话
          password: '',   // 密码
          proxyRegion: '',    // 服务地区
          enable: '1',    // 是否启用
          serviceCenter: {    // 服务中心
            location: {
              O: 0,
              P: 0,
              lat: 0,
              lng: 0
            },
            isSelect: false
          },
          serviceRegionGroup: [
            // {
            //	   weight:'',			//首重
            //     weightprice:'',		//首重价格
            //     distance:'',		//续重
            //     distanceprice:'',
            //     sdistance:'',		//起步距离
            //     sdistanceprice:'',
            //     addstart:'',		//增加距离
            //     addstartprice:'',
            //     location: {},   // 地图对象
            // }
          ]
        },
        mapConfigForm: {
          editorStatus: 0,
          weight: '',			//首重
          weightprice: '',		//首重价格
          distance: '',		//续重
          distanceprice: '',
          sdistance: '',		//起步距离
          sdistanceprice: '',
          addstart: '',		//增加距离
          addstartprice: '',
          currentEditorIndex: -1
        },
        addressSearchForm: {
          keywords: '',
          location: null,
        },
        windowAlert: {
          hintText: '',
          isShow: false,
          defaultTimeOut: 2000
        },
        ruleForm: {
          name: ''
        },
        rules: {
          name: [
            {required: true, message: '请输入活动名称', trigger: 'blur'},
            {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
          ]
        }
      }
    },
    mounted: function () {
      let _this = this;
      // 地图一
      map = new AMap.Map("map-container", {
        resizeEnable: true,
        // center: [116.403322, 39.900255],//地图中心点
        // zoom: 15 //地图显示的缩放级别
      });

      //在地图中添加MouseTool插件
      AMap.service('AMap.MouseTool', function () {
        mouseTool = new AMap.MouseTool(map);
      });

      /**
       * 双击结束绘制
       * */
      map.on('dblclick', function () {
        if (polygonDrawUtil.drawStatus) {
          polygonDrawUtil.getCurrentPolygonDraw();
          polygonDrawUtil.drawStatus = false;
        }
      })

      // 地图二
      mapContainer = new AMap.Map('mapContainer', {
        resizeEnable: true
      });

      // 地图中添加地图操作ToolBar插件
      mapContainer.plugin(['AMap.ToolBar'], function () {
        //设置地位标记为自定义标记
        toolBar = new AMap.ToolBar();
        mapContainer.addControl(toolBar);
      });

      mapContainer.on('click', function (e) {
        _this.addressSearchForm.location = e.lnglat;
        let icon = 'https://www.135k.com/addons/sd_liferuning/tp/public/static/home/img/shop_marker.png';
        polygonDrawUtil.addMarker({map: mapContainer, icon: icon, location: _this.addressSearchForm.location})
      });

      polygonConfig = {
        map: map
      }

      polygonDrawUtil = new PolygonDrawUtil({mouseTool: mouseTool, polygonConfig: polygonConfig});
    }
  }


  let map;
  let mouseTool;  // 工具句柄
  let polygonDrawUtil;  // 工具


  let mapContainer;
  let toolBar;
  let msearch;


  // 配置参数
  let polygonConfig;

  /*
   * 多边形绘制工具
   * @auth MrNan
   */
  class PolygonDrawUtil {
    /**
     * @param mouseTool 工具句柄
     * @param polygonConfig 绘制配置文件
     */
    constructor({mouseTool: mouseTool, polygonConfig: polygonConfig}) {
      this.mouseTool = mouseTool;
      this.polygonConfig = polygonConfig;
      this.tempPolygon = null;
      this.beforeSize = 0;
      this.currentSize = 0;
      this.drawStatus = false;
    }

    /**
     * 绘制
     */
    beginDraw() {
      this.mouseTool.polygon(this.polygonConfig);
      this.tempPolygon = null;
      this.drawStatus = true;
    }

    /**
     * 结束编辑并返回当前的绘制的多边形
     * @param map
     */
    getCurrentPolygonDraw() {
      this.mouseTool.close(false);
      let arr = this.polygonConfig.map.getAllOverlays();
      this.currentSize = arr.length;
      if (this.currentSize > this.beforeSize) {
        this.beforeSize = this.currentSize;
        this.tempPolygon = arr[this.currentSize - 1];
      }
    }

    /**
     * 结束编辑,并清除绘制
     * */
    closeDrawSlsoClear() {
      this.getCurrentPolygonDraw();
      if (this.tempPolygon) {
        this.polyDelete({PolygonObject: this.tempPolygon});
      }
    }

    /**
     * 开启折线的编辑状态
     * @param PolygonObject
     */
    polyEditor({map: map, PolygonObject: PolygonObject}) {
      let _this = this;
      map.plugin(["AMap.PolyEditor"], function () {
        _this.polylineEditor = new AMap.PolyEditor(map, PolygonObject);
        _this.polylineEditor.open();
      });
    }

    /**
     * 关闭折线的编辑状态
     * @param PolygonObject
     */
    polyEditorSave({map: map, PolygonObject: PolygonObject}) {
      map.plugin(["AMap.PolyEditor"], function () {
        let polylineEditor = new AMap.PolyEditor(map, PolygonObject);
        polylineEditor.close();
      });
      this.polylineEditor.close();
    }

    /**
     * 删除折线覆盖物
     */
    polyDelete({PolygonObject: PolygonObject}) {
      this.polygonConfig.map.remove(PolygonObject);
    }

    /**
     * 获取折线对象路径信息
     */
    polyGetPath({PolygonObject: PolygonObject}) {
      return PolygonObject.getPath();
    }

    /**
     * 添加标记,并锁定中心区域为位置对象的坐标点区域
     */
    addMarker({map: map, icon: icon, location: location}) {
      let marker = new AMap.Marker({
        position: new AMap.LngLat(location.O, location.P),
        icon: icon
      });
      map.clearMap();
      map.add(marker);
      map.setCenter(location);
      map.setZoom(18);
    }
  }


</script>

<style scoped>
  .el-container {
    display: block;
  }

  .el-form {
    width: 1000px;
    margin: 15px 30px;
  }

  .map-container {
    width: 100%;
    height: 500px;
  }

  /*编辑*/
  .add-mapconfig {
    border-radius: 5px;
    margin: 10px 0;
    border-left: 5px solid #e5b383;
    padding: 5px;
    font-size: 12px !important;
  }

  .mapconfig-title {
    display: flex;
    justify-content: space-between;
    line-height: 25px;
    margin: 5px 0;
    padding: 0 5px;
    font-size: 12px !important;
  }

  .mapconfig-input-group {
    display: flex;
    overflow: hidden;
    margin: 5px 0;
    font-size: 12px !important;
  }

  .mapconfig-input-group .label {
    width: 50px !important;
    background: #ffffff;
    color: #111111;
    font-weight: normal;
    font-size: 12px !important;
  }

  .mapconfig-input-group .input-text {
    width: 90px;
    font-size: 12px !important;
  }

  .mapconfig-input-group .unit {
    margin-left: 10px;
    font-size: 12px !important;
  }

  .mapconfig-info {
    border-left: 5px solid #00CC99;
    padding: 5px;
    border-radius: 5px;
    margin: 10px 0;
    overflow: hidden;
    font-size: 12px !important;
  }
  .mapconfig-info p{
    margin: 5px;
  }

  .edit-btn {
    float: right;
    margin-top: 5px;
    font-size: 12px !important;
  }

  /* 地图 */
  .address-map-container{
    min-height: 600px;
    min-width: 900px !important;
  }
  .address-map-container .modal-body{
    margin: 0;
    padding: 0;
    width: 900px !important;
  }
  .address-map-container .address-map{
    height: 600px;
    width: 898px;
  }
  .address-map-container .input-group{
    width: 500px;
    display: flex;
    margin: 0 auto;
    float: right;
  }
  .modal-title{
    width: 100%;
  }

</style>
